<?php

namespace App\Http\Controllers;

use App\Exports\InstructorsExport;
use App\Http\Controllers\Controller;
use App\Http\Filters\InstructorsFilter;
use App\Http\Requests\Centers\CentersUpdateRequest;
use App\Http\Requests\Instructors\InstructorsStoreRequest;
use App\Http\Requests\Instructors\InstructorsUpdateRequest;

use App\Http\Requests\Instructors\FilterRequest;
use App\Http\StaticData;
use App\Models\Centers;
use App\Models\Instructors;
use App\Models\Members;
use App\Models\Reports;
use App\Models\Sport;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class InstructorsController extends Controller
{
    use StaticData;
    public function show(FilterRequest $request) {

       $data = $request->validated();






        $currentCenters = [];

        foreach ( User::find(Auth::id())->centers as $center) {
            $currentCenters[] = $center->id;
        }

        if (!in_array(3,$currentCenters)) {
            $centers = Centers::where('user_id', Auth::id())->get();
        } else {
            $centers = Centers::all();
        }
        if (isset($data['filters'])) {
            if (!isset($data['filters']['centers_id'])) {
                $data['filters']['centers_id'] = $centers->pluck('id')->toArray();
            }
            $filter = app()->make(InstructorsFilter::class,['queryParams' => array_filter($data['filters'])]);

            $instructors = Instructors::filter($filter)->paginate(30);
        } else {
            if (!isset($data['filters']['centers_id'])) {
                $filterCenter['centers_id'] = $centers->pluck('id')->toArray();
            }
            $filter = app()->make(InstructorsFilter::class,['queryParams' => array_filter($filterCenter)]);
            $instructors = Instructors::filter($filter)->paginate(30);
        }

        $sports = $this->sports;
        $status = $this->instructorStatus;


        $totalItems = $instructors->total();
        $currentPage = $instructors->currentPage();
        $perPage = 30;



        return view('instructors.show', compact('status','sports','instructors','centers', 'totalItems', 'currentPage', 'perPage' ));
    }



    public function edit(Instructors $instructor) {
        $currentCenters = [];

        foreach ( User::find(Auth::id())->centers as $center) {
            $currentCenters[] = $center->id;
        }

        if (!in_array(3,$currentCenters)) {
            $centers = Centers::query();
            $centers->whereIn('id',$currentCenters);
            $centers = $centers->get();
        } else {
            $centers = Centers::all();
        }

        $sports = Sport::all();
        $instructorSports = $instructor->sports;
        $instructorSportsIds = $instructorSports->pluck('id')->toArray();

        return view('instructors.edit', compact('instructor','instructorSportsIds','centers','sports'));

    }

    public function update(InstructorsUpdateRequest $request,Instructors $instructor) {


        $data = $request->validated();

        if (Arr::get($data, 'photo')) {
            $imagePath = $this->generateImagePath(Arr::get($data, 'photo'));
            $data['photo'] = $imagePath;
        } else {
            $data['photo'] = 'no-image';
        }


        $instructor->update([
            'name' => $data['name'],
            'surname' => $data['surname'],
            'second_name' => $data['second_name'],
            'status' => $data['status'],
            'recertification' => $data['recertification'],
            'centers_id' => $data['centers_id'],
            'photo' => $data['photo'],
            'gender' => $data['gender'],
            'cert_valid' => $data['cert_valid']
        ]);
        if ($request->has('sports')) {
            $instructor->sports()->sync($data['sports']);
        }

        $instructor->save();

        return redirect(route('instructors'));
    }
    public function add(Request $request) {

        $currentCenters = [];

        foreach ( User::find(Auth::id())->centers as $center) {
            $currentCenters[] = $center->id;
        }
        if (!in_array(3,$currentCenters)) {
            $centers = Centers::query();
            $centers->whereIn('id',$currentCenters);
            $centers = $centers->get();
        } else {
            $centers = Centers::all();
        }

        $sports = Sport::all();



        return view('instructors.add', compact('centers','sports'));
    }

    public function inactiveadd(Request $request) {


        $currentCenters = [];

        foreach ( User::find(Auth::id())->centers as $center) {
            $currentCenters[] = $center->id;
        }
        if (!in_array(3,$currentCenters)) {
            $centers = Centers::query();
            $centers->whereIn('id',$currentCenters);
            $centers = $centers->get();
        } else {
            $centers = Centers::all();
        }


        $instructors = Instructors::where('active', 0)->get();


        return view('instructors.inactiveadd', compact('instructors','centers'));
    }

    public function store(InstructorsStoreRequest $request) {

        $data = $request->validated();

        if (Arr::get($data, 'photo')) {
            $imagePath = $this->generateImagePath(Arr::get($data, 'photo'));
            $data['photo'] = $imagePath;
        } else {
            $data['photo'] = 'no-image';
        }


        $instructor = Instructors::create([
            'name' => $data['name'],
            'surname' => $data['surname'],
            'second_name' => $data['second_name'],
            'status' => $data['status'],
            'recertification' => $data['recertification'],
            'centers_id' => $data['centers_id'],
            'photo' => $data['photo'],
            'gender' => $data['gender'],
            'cert_valid' => $data['cert_valid']
        ]);
        if ($request->has('sports')) {
            $instructor->sports()->attach($data['sports']);
        }

        $instructor->save();

        return redirect(route('instructors'));
    }

    public function storeinactive(Request $request) {


        $instructor = Instructors::find($request->instructors);

        $instructor->update(['active' => 1, 'centers_id' => $request->centers_id]);
        return redirect(route('instructors'));
    }

    public function delete(Request $request, Instructors $instructor) {

        $forDelete = Instructors::find($instructor->id);
        if (!$forDelete->delete()){
            throw new \Exception('Невозможно удалить запись');
        } else {
            return redirect(route('instructors'));
        }

    }


    protected function generateImagePath($image): string
    {
        return Storage::put('photos', $image);
    }
}
